﻿using System.Web.Mvc;
using ECommerce.Web.Commands;
using ECommerce.Web.ViewModels;
using ECommerce.Web.ViewQueries;
using MvcContrib;

namespace ECommerce.Web.Controllers
{
    public class BasketController : BaseController
    {
        private readonly IBasketViewQuery basketViewQuery;
        private readonly IAddProductToBasketCommand addProductToBasketCommand;
        private readonly IChangeProductQuantitiesInBasketCommand changeProductQuantitiesInBasketCommand;
        private readonly IRemoveProductFromBasketCommand removeProductFromBasketCommand;

        public BasketController(
            IBasketViewQuery basketViewQuery,
            IAddProductToBasketCommand addProductToBasketCommand,
            IChangeProductQuantitiesInBasketCommand changeProductQuantitiesInBasketCommand,
            IRemoveProductFromBasketCommand removeProductFromBasketCommand)
        {
            this.basketViewQuery = basketViewQuery;
            this.addProductToBasketCommand = addProductToBasketCommand;
            this.changeProductQuantitiesInBasketCommand = changeProductQuantitiesInBasketCommand;
            this.removeProductFromBasketCommand = removeProductFromBasketCommand;
        }

        public ActionResult Index()
        {            
            BasketView basketView = this.basketViewQuery.GetQuery();

            return View(basketView);
        }

        [HttpPost]
        public ActionResult AddProduct(AddProductToBasketMessage addProductToBasketMessage)
        {
            InvokeCommand(() => this.addProductToBasketCommand.Handle(addProductToBasketMessage));

            return this.RedirectToAction(x => x.Index());
        }

        [HttpPost]
        public ActionResult ChangeProductQuantities(ChangeProductQuantitiesInBasketMessage changeProductQuantitiesInBasketMessage)
        {
            if (!ModelState.IsValid) { return this.RedirectToAction(x => x.Index()); }

            InvokeCommand(() => this.changeProductQuantitiesInBasketCommand.Handle(changeProductQuantitiesInBasketMessage));

            return this.RedirectToAction(x => x.Index()); 
        }

        [HttpPost]
        public ActionResult RemoveProduct(int id)
        {
            InvokeCommand(() => this.removeProductFromBasketCommand.Handle(id));

            return this.RedirectToAction(x => x.Index());
        }
    }
}
